package com.softer.chengxin.sysscore.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.common.domin.CommonResult;
import com.softer.chengxin.common.domin.Page;
import com.softer.chengxin.common.enums.ResultEnum;
import com.softer.chengxin.sysscore.dao.SysScoreTypeDao;
import com.softer.chengxin.sysscore.entity.SysScoreTypeDTO;
import com.softer.chengxin.sysscore.service.SysScoreTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author zcz
 * @date 2018/12/12
 */
@Service
public class SysScoreTypeServiceImpl implements SysScoreTypeService {
    @Autowired
    private SysScoreTypeDao scoreTypeDao;

    @Override
    public List<SysScoreTypeDTO> getScoreTypeList(Page page, SysScoreTypeDTO scoreTypeDTO) {
        return scoreTypeDao.getScoreTypeList(page, scoreTypeDTO);
    }

    @Override
    public CommonResult add(String list, String scoreType ,String loginName) {
        //参数
        if(StringUtils.isBlank(list)){
            return new CommonResult(ResultEnum.FAIL.getCode(),"参数为空！");
        }
        //list参数进行转码
        try{
            list = URLDecoder.decode(list,"utf-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        List<SysScoreTypeDTO> scoreTypeDTOList = JSONArray.parseArray(list, SysScoreTypeDTO.class);
        int i = 0;
        for ( SysScoreTypeDTO s:scoreTypeDTOList) {
            s.setScoreType(scoreType);
            s.setAdder(loginName);
            i = scoreTypeDao.add(s);
        }
        return getResult(i);
    }

    @Override
    public CommonResult update(SysScoreTypeDTO scoreTypeDTO) {
        int i = scoreTypeDao.update(scoreTypeDTO);
        return getResult(i);
    }

    @Override
    public CommonResult delete(String id) {
        int i = scoreTypeDao.delete(id);
        return getResult(i);
    }

    @Override
    public SysScoreTypeDTO getScoreTypeById(String id) {
        return scoreTypeDao.getScoreTypeById(id);
    }

    @Override
    public List<SysScoreTypeDTO> getScoreTypeListByScoreType(String scoreType) {
        return scoreTypeDao.getScoreTypeListByScoreType(scoreType);
    }

    @Override
    public int getScoreTypeCount(SysScoreTypeDTO scoreTypeDTO){
        return scoreTypeDao.getScoreTypeCount(scoreTypeDTO);
    }
    /**
     * 返回处理结果
     *
     * @param num 数据库执行的条数
     * @return 结果
     */
    private CommonResult getResult(int num) {
        if (num > Integer.parseInt(Common.ZERO)) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), Common.OPERATE_SUCCESS);
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), Common.OPERATE_FAIL);
    }

}
